<template>
  <el-dialog title="新增案件" :visible.sync="show" :before-close="handleClose" center width="800px">
    <div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="案件标题">
          <el-input v-model="form.title" clearable placeholder="案件标题"></el-input>
        </el-form-item>
        <el-form-item label="用户id">
          <el-input @blur="userIdIptBlurEvent" v-model="form.userId" clearable placeholder="用户id"></el-input>
        </el-form-item>
        <el-form-item label="用户手机">
          <el-input v-model="userMobileNo" disabled placeholder="用户手机"></el-input>
        </el-form-item>
        <el-form-item label="案件地区">
          <Region @getRegion="getRegion" placeholder="案件地区"/>
        </el-form-item>
        <el-form-item label="案件类型">
          <CaseTypeSelect @getCaseType="getCaseType" placeholder="案件类型"/>
        </el-form-item>
        <el-form-item label="案件详情">
          <quill-editor v-model="form.content"
              placeholder='fsfsf'
              ref="myQuillEditor"
              :options="editorOption"
              @change="onEditorChange">
          </quill-editor>
          <input v-show='false' type="file" @change="upfile" id='upImg' ref="upImg" accept="image/png, image/jpeg, image/gif, image/jpg" />
          <!-- <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="form.content"></el-input> -->
        </el-form-item>
        <el-form-item label="律师ID">
          <el-input @blur="lawyerIdIptBlurEvent" v-model="form.lawyerId" clearable placeholder="律师ID"></el-input>
        </el-form-item>
        <el-form-item label="律师姓名">
          <el-input v-model="lawyerName" disabled placeholder="输入ID回显"></el-input>
        </el-form-item>
        <el-form-item label="律师手机">
          <el-input v-model="lawyerMobileNo" disabled placeholder="输入ID回显"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import CaseTypeSelect from "../../components/CaseTypeSelect";
import Region from "../../components/Region";
import config from '../../config';
export default {
  name: "AddCase",
  components: {
    Region: Region,
    CaseTypeSelect: CaseTypeSelect
  },
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editorOption: { 
        theme: 'snow',
        placeholder: '请在此输入咨询记录...',
        modules: {
          toolbar: {
            container: config.toolbarOptions,
            handlers: {
              'image': function(value) {
                if(value) {
                  document.querySelector('#upImg').click()
                } else {
                  this.quill.format('image', false);
                }
                
              }
            }
          }
        }
      }, // 富文本配置
      caseType: "",
      region: "",
      form: {
        title: '',
        userId: '',
        content: '',
        lawyerId: '',
        province: '',
        city: '',
        caseType: '',
      },
      isUserId: false,
      isLawyerId: false,
      userMobileNo: '',
      lawyerName: '',
      lawyerMobileNo: '',
      showDialog: false,
      value: "",
      caseTypeList: []
    };
  },
  created() {
    console.log("show:::", this.show);
  },
  methods: {
    // 上传
    upfile(e) {
      const files = e.target.files;
      const form = new FormData();
      form.append("file", files[0]);
      form.append("dir", "notice");
      form.append("type", "1");
      this.$store.dispatch("UPLOAD_FILE", form).then(res => {
        if (res.data.retCode == 0) {
          this.$message.success("上传成功！");
          // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data.data)
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    onEditorChange({ quill, html, text }) {
      console.log('editor change!-quill', quill, html, text)
      console.log('editor change!-html', html)
      console.log('editor change!-text', text)
      this.form.content = html;
    },
    init() {
      this.form = {
        title: '',
        userId: '',
        content: '',
        lawyerId: '',
        province: '',
        city: '',
        caseType: '',
      }
      this.isUserId= false;
      this.isLawyerId= false;
      this.userMobileNo= '';
      this.lawyerName= '';
      this.lawyerMobileNo= '';
    },
    // 确定按钮点击事件
    onSubmit() {
      if(this._utils.isEmpty(this.form.title)) {
        this.$message.warning('请输入案件标题！');
        return;
      }
      if(!this.isUserId) {
        this.$message.warning('请输入正确的用户id！');
        return;
      }
      if(this._utils.isEmpty(this.form.province) || this._utils.isEmpty(this.form.city)) {
        this.$message.warning('请选择地区！');
        return;
      }
      if(this._utils.isEmpty(this.form.caseType)) {
        this.$message.warning('请选择案件类型！');
        return;
      }
      if(this._utils.isEmpty(this.form.content)) {
        this.$message.warning('请输入案件详情！');
        return;
      }
      if(!this.isLawyerId) {
        this.$message.warning('请输入正确的律师id！');
        return;
      }
      this.addCase();
    },

    // 新增案件
    addCase() {
      this.$store.dispatch('ADD_CASE', {
        userId: this.form.userId,
        title: this.form.title,
        province: this.form.province,
        city: this.form.city,
        caseType: this.form.caseType,
        content: this.form.content,
        lawyerId: this.form.lawyerId
      }).then(res => {
        if(res.data.retCode == 0) {
          console.log('addCase:::', res);
          this.$message.success('新增成功！');
          this.handleClose();
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    // 用户id输入框失去焦点事件
    userIdIptBlurEvent() {
      console.log(this.form.userId);
      if (/^\d+$/.test(this.form.userId)) {
        this.getUserById(this.form.userId);
      } else {
        this.$message.warning("请输入正确id格式，id为纯数字");
      }
    },
    // 律师id输入框失去焦点事件
    lawyerIdIptBlurEvent() {
      if (/^\d+$/.test(this.form.lawyerId)) {
        this.getLawyerById(this.form.lawyerId);
      } else {
        this.$message.warning("请输入正确id格式，id为纯数字");
      }
    },
    getLawyerById(lawyerId) {
      this.$store.dispatch('GET_LAWYER_BY_ID', {
        id: lawyerId
      }).then(res => {
        if(res.data.retCode == 0) {
          console.log('detail:::', res);
          this.isLawyerId = true;
          this.lawyerMobileNo = res.data.data.mobileNo;
          this.lawyerName = res.data.data.name;
        } else {
          this.isLawyerId = false;
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    // 根据userId获取用户信息
    getUserById(userId) { // 根据用户id查询用户信息
      this.$store.dispatch('QUERY_USER', {
        id: userId
      }).then(res => {
        console.log('res::', res);
        if(res.data.retCode == 0) {
          if(res.data.data) {
            this.userMobileNo = res.data.data.mobileNo;
            this.isUserId = true;
          } else {
            this.$message.warning('用户id不存在');
            this.form.userMobileNo = '';
            this.isUserId = false;
          }
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    // dialog关闭前处理
    handleClose() {
      this.init();
      this.$emit("close");
    },

    // 获取地区
    getRegion(obj) {
      if(obj.hasOwnProperty('province')) {
        this.form.province = obj.province.id;
      } else {
        this.form.province = '';
      }
      if(obj.hasOwnProperty('city')) {
        this.form.city = obj.city.id;
      } else {
        this.form.city = '';
      }
    },
    getCaseType(caseType) {
      this.form.caseType = caseType;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
